from PySide6 import QtGui, QtWidgets, QtCore
from devicectrl import CtrlWindowUI
import common.globaldefines
import labelmanager

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ctrlUI = CtrlWindowUI()
        self.setCentralWidget(self.ctrlUI)
        self.setWindowTitle("GameAutoLabel v0.0.1")

        self._copySource = ""

        self.initUI()

    def initUI(self):
        self.leftTopDockWidget = QtWidgets.QDockWidget(self)
        self.addDockWidget(QtCore.Qt.DockWidgetArea.LeftDockWidgetArea, self.leftTopDockWidget)
        self.leftTopDockWidget.resize(100, 300)

        self.leftDockWidget = QtWidgets.QDockWidget(self)
        self.projects = QtWidgets.QTreeWidget()
        self.leftDockWidget.setWidget(self.projects)
        self.addDockWidget(QtCore.Qt.DockWidgetArea.LeftDockWidgetArea, self.leftDockWidget)
        self.leftDockWidget.resize(100, self.height())


        self.projects.itemDoubleClicked.connect(self.onOpenLabelInfo)
        self.projects.itemPressed.connect(self.onClickedItem)

        self.initHostUI()

    def initHostUI(self):
        self.hostGroupWidget = QtWidgets.QGroupBox()
        self.leftTopDockWidget.setWidget(self.hostGroupWidget)
        l = QtWidgets.QVBoxLayout()
        self.hostGroupWidget.setLayout(l)
        self.hostInfo = QtWidgets.QComboBox(self.hostGroupWidget)

        self.hostGroupWidget.layout().addWidget(self.hostInfo)

        self.connectBtn = QtWidgets.QPushButton("Connect")
        self.hostGroupWidget.layout().addWidget(self.connectBtn)


    def onStarted(self):
        import application
        application.Application.instance()._screenUpdateCallbacks.append(self.updateScreen)
    
    def onClickedItem(self):
        if QtWidgets.QApplication.instance().mouseButtons() != QtCore.Qt.MouseButton.RightButton:
            return
        item = self.projects.currentItem()
        menu = QtWidgets.QMenu(self.projects)
        action1 = QtGui.QAction("Rename")
        action2 = QtGui.QAction("Disable")
        action3 = QtGui.QAction(f"Copy \"{item.text(0)}\"")
        action4 = QtGui.QAction(f"Patse \"{self._copySource}\"")
        if not self._copySource:
            action4.setEnabled(False)
        action6 = QtGui.QAction(f"Remove \"{item.text(0)}\"")
        menu.addAction(action1)
        menu.addAction(action2)
        menu.addAction(action3)
        menu.addAction(action4)
        menu.addSeparator()
        menu.addAction(action6)
        a = menu.exec(QtGui.QCursor.pos())
        DebugPrint(a)

        if a == action1:
            suc = True
            title = f"Project \"{item.text(0)}\" rename"
            txt = "New name"
            while suc:
                name = QtWidgets.QInputDialog(self, title, txt).getText()
                if name in labelmanager.g_Instance.getAllGroup():
                    txt = f"{name} already exist."
                else:
                    labelmanager.g_Instance.renameGroup(item.text(0), name)
                    item.setText(0, name)
                    suc = False
                    break
        elif a == action3:
            self._copySource = item.text(0)
            DebugPrint(f"Copy {item.text(0)}...")
        elif a == action4:
            if not self._copySource:
                return
            newname = f"copy {item.text(0)}"
            i = 1
            allgroups = labelmanager.g_Instance.getAllGroup()
            while i > 9999:
                if newname not in allgroups:
                    newname = f"{newname}({i})"
                    break
                i += 1
            newitem = QtWidgets.QTreeWidgetItem()
            newitem.setText(0, newname)
            self.projects.addTopLevelItem(newitem)
            labelmanager.g_Instance.addGroup(newname)
        elif a == action6:
            ret = QtWidgets.QMessageBox.warning(self, f"注意",
                               f"确认要删除分组\"{item.text(0)}\"吗？",
                               QtWidgets.QMessageBox.StandardButton.Ok | QtWidgets.QMessageBox.StandardButton.Cancel)
            DebugPrint(">>>", ret)



    def onOpenLabelInfo(self):
        text = self.projects.currentItem().text(0)
        self.ctrlUI._title = text
        self.ctrlUI._displaywidget._title = text
        self.ctrlUI.refreshLabelsUI()

    def updateScreen(self, img):
        self.ctrlUI.updateScreen(img)

    def closeEvent(self, event):
        import application
        application.Application.instance().exit()
        return super().closeEvent(event)
    
    def OpenProject(self, projectFile):
        labelmanager.g_Instance.loadProject(projectFile)
        for title in labelmanager.g_Instance._labels.keys():
            item = QtWidgets.QTreeWidgetItem()
            item.setText(0, title)
            self.projects.addTopLevelItem(item)
            #self.ctrlUI._title = title
            #self.ctrlUI._displaywidget._title = title